<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="帖子详情"
      @click-left="$router.back()"
      fixed
    ></van-nav-bar>
    <!-- /导航栏 -->

    <!-- 内容区域 - 可滚动区域 -->
    <div class="main-wrap">
      <!-- 加载中 - 作用仅是获取数据时的动画表现 -->
      <div class="loading-wrap" v-if="isLoading">
        <van-loading
          color="#3296fa"
          vertical
        >加载中
        </van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="articleInfo.art_id">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ articleInfo.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <!-- 头像 -->
          <template #icon>
            <van-image
              class="avatar"
              round
              fit="cover"
              :src="articleInfo.aut_photo"
            />
          </template>

          <template #title>
            <div class="user-name">{{ articleInfo.aut_name }}</div>
          </template>

          <template #label>
            <div class="publish-date">{{ articleInfo.pubDate | relativeTime }}</div>
          </template>
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          ref="article-content"
          class="article-content markdown-body"
          v-html="articleInfo.content"
        ></div>
        <van-divider>正文结束</van-divider>

        <!-- 文章评论列表区域 -->
        <comment-list
          ref="comment-list"
          :sourceId="articleInfo.art_id"
          @onloadSuccess="onloadSuccessFn"
          @replyClick="replyClickFn"
        ></comment-list>
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="articleInfo.message !== 0">
        <van-icon name="failure"/>
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure"/>
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadGetArticle">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom">
      <!-- 写评论按钮 -->
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="isPostShow = true"
      >写评论
      </van-button>

      <!-- 评论数量显示 -->
      <van-icon
        name="comment-o"
        :badge="totalCommentCount"
        color="#777"
      />

      <!-- 收藏文章 -->
      <collect-article
        :isCollected.sync="articleInfo.is_collected"
        :articleId="articleInfo.art_id"
      ></collect-article>

      <!-- 点赞文章 -->
      <like-article
        :attitude.sync="articleInfo.attitude"
        :articleId="articleInfo.art_id"
      ></like-article>

      <!-- 分享转发 -->
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->

    <!-- 弹框部分，写在整个模板的最下面 -->
    <!-- 评论提交弹框 -->
    <van-popup v-model="isPostShow" position="bottom">
      <comment-post
        :targetId="articleInfo.art_id"
        @postSuccess="postSuccessFn"
      ></comment-post>
    </van-popup>

    <!-- 评论回复弹框 -->
    <van-popup v-model="isReplyShow" position="bottom" style="height: 100%;">
      <comment-reply
        v-if="isReplyShow"
        :comment="currentReplyComment"
        @closeReply="isReplyShow = false"
      ></comment-reply>
    </van-popup>
  </div>
</template>

<script>
import { getArticleByIdAPI } from '@/api'
import { ImagePreview } from 'vant'
// import FollowUser from './components/follow-user.vue'
import CollectArticle from './components/collect-article.vue'
import LikeArticle from './components/like-article.vue'
import CommentList from './components/comment-list.vue'
import CommentPost from './components/comment-post.vue'
import CommentReply from './components/comment-reply.vue'

export default {
  name: 'ArticleIndex',
  components: {
    // FollowUser,
    CollectArticle,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply
  },
  data () {
    return {
      isLoading: false, // 加载状态
      errorStatus: 200, // 失败时的状态码
      articleInfo: {}, // 文章详情信息
      totalCommentCount: 0, // 文章评论总数量
      isPostShow: false, // 写评论弹框状态
      isReplyShow: false, // 评论回复弹框状态
      currentReplyComment: {} // 评论回复弹框中的目标文章评论内容
    }
  },
  created () {
    // 调用获取文章详情的方法
    this.loadGetArticle()
    console.log(this.$route.params.articleId)
  },

  methods: {
    // 触发评论回复弹框内容
    replyClickFn (currentComment) {
      // 将子组件传递过来的评论对象赋值给 currentReplyComment
      this.currentReplyComment = currentComment
      console.log('currentComment', currentComment)

      // 开启评论回复弹框
      this.isReplyShow = true
    },

    // 发布评论成功后触发的方法
    postSuccessFn (newComment) {
      this.isPostShow = false
      this.$refs['comment-list'].addComment(newComment)
    },

    // 文章列表更新成功后触发的方法
    onloadSuccessFn (total) {
      // 记录评论总数
      this.totalCommentCount = total
    },

    // 更新关注状态
    changeIsFollowedFn (newStatus) {
      this.articleInfo.is_followed = newStatus
    },

    // 获取文章详情
    async loadGetArticle () {
      try {
        // 调用接口前，改为true
        this.isLoading = true

        const { data: res } = await getArticleByIdAPI(this.$route.params.articleId)
        this.articleInfo = res.data
        console.log(this.articleInfo)

        // 获取所有的文字图片内容
        setTimeout(() => {
          this.previewImage()
        }, 0)
      } catch (error) {
        console.log(error)
        // 先查看报错信息有无响应参数，在判断参数中的code是否为404
        if (error.response && error.response.status === 404) {
          this.errorStatus = 404
        }
        this.$toast.fail('获取详情失败')
      }

      // 无论成功失败，都需要关闭加载状态
      this.isLoading = false
    },

    // 初始化图片预览功能
    previewImage () {
      // 1. 获取到所有的img标签节点
      const articleContent = this.$refs['article-content']
      const domImgs = articleContent.querySelectorAll('img')

      // 2. 获取图片列表
      const images = [...domImgs].map(img => img.src)

      // 3. 遍历每一个元素，为他们绑定点击事件查看大图
      domImgs.forEach((img, index) => {
        img.onclick = () => {
          ImagePreview({
            images: images,
            startPosition: index
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
@import './styles/github-markdown.css';

.article-container {
  background-image: linear-gradient(to bottom, #ffc0cb, #fcd0e2, #f8e1f3, #f8f1fc, #ffffff);

  ::v-deep .van-nav-bar {
    background-color: #ffc1cc;
    border: none;

    .van-nav-bar__content {
      height: 8vh;
      font-size: 16px;
      letter-spacing: 1px;
    }

    &::after {
      border: none;
    }
  }

  .main-wrap {
    padding-top: 46px;
    padding-bottom: 44px;
    overflow-y: scroll;
    background-image: linear-gradient(to bottom, #ffc0cb, #fcd0e2, #f8e1f3, #f8f1fc, #ffffff);
  }

  .article-detail {
    .article-title {
      font-size: 20px;
      padding: 25px 16px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 16px;
      background-color: transparent;

      .avatar {
        width: 35px;
        height: 35px;
        margin-right: 9px;
      }

      .van-cell__label {
        margin-top: 0;
      }

      .user-name {
        font-size: 12px;
        color: #3a3a3a;
      }

      .publish-date {
        font-size: 12px;
        color: #b7b7b7;
      }

      .follow-btn {
        width: 85px;
        height: 29px;
      }
    }

    .article-content {
      padding: 27.5px 16px;

      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 100px 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 100px 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;

    .van-icon {
      font-size: 61px;
      color: #b4b4b4;
    }

    .text {
      font-size: 15px;
      color: #666666;
      margin: 16px 0 23px;
    }

    .retry-btn {
      width: 140px;
      height: 35px;
      line-height: 35px;
      //border: 1px solid #c3c3c3;
      font-size: 15px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 44px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;

    .comment-btn {
      width: 141px;
      height: 23px;
      border: 1px solid #eeeeee;
      font-size: 15px;
      line-height: 23px;
      color: #a7a7a7;
    }

    .van-icon {
      font-size: 20px;

      .van-info {
        font-size: 8px;
        background-color: #e22829;
      }
    }
  }
}
</style>
